from fastapi import APIRouter, Depends
from ..schemas import MenuInSchema, MenuOutSchema, MenuOutTreeSchema
from ..models import Menu, UserInfo
from typing import List
from src.utils.common_response import APIResponse

router = APIRouter()


@router.get('/menus', description='查询所有子菜单')
async def get_menu_list():
    menus = await Menu.filter(is_delete=False, pid=None).all().prefetch_related('children')
    menu_dicts = [await MenuOutSchema.from_orm_recursive(menu) for menu in menus]
    return APIResponse(results=menu_dicts)


@router.post('/menus', description='菜单新增')
async def add_menu(menu: MenuInSchema):
    await Menu.create(**menu.dict())
    return APIResponse(msg='新增成功')


@router.delete("/menus", description='删除接口，单条多条都支持')
async def delete_menu(ids: List[int]):
    res = await Menu.filter(id__in=ids).update(is_delete=True)
    return APIResponse(msg="菜单新增成功")


@router.get("/menus/{meun_id}", description="查询菜单详情")
async def get_menu(menu_id: int):
    menu = await Menu.filter(id=menu_id, is_delete=False, pid=None).prefetch_related('children').first()
    menu_dict = await MenuOutSchema.from_orm_recursive(menu)
    return APIResponse(result=menu_dict)


@router.put("/menu/{menu_id}", description="修改菜单详情")
async def update_menu(menu_id: int, menu: MenuInSchema):
    await Menu.filter(id=menu_id).update(**menu.dict())
    return APIResponse(msg="菜单修改成功")


@router.get("/tree/menus", description='查询所有菜单')
async def get_menu_list_tree():
    menus = await Menu.filter(is_delete=False, pid=None).all().prefetch_related('children')
    menus_dicts = [await MenuOutTreeSchema.from_orm_recursive(menu) for menu in menus]
    return APIResponse(results=menus_dicts)
